package com.alibaba.demo.common.exceptionhandler;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.alibaba.demo.domain.core.exception.ServiceException;
import com.alibaba.demo.domain.core.exception.ServiceExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.sql.SQLSyntaxErrorException;
import java.util.List;

/**
 * @author Administrator
 * @date 2024/4/28 16:24
 * @description
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response handleValidException(MethodArgumentNotValidException exp) {
        List<FieldError> fieldErrors = exp.getBindingResult().getFieldErrors();
        StringBuilder msgError = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            msgError.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(" | ");
        }
        if (msgError.length() > 0) {
            msgError.replace(msgError.lastIndexOf(" | "), msgError.length(), "");
        }
        return Response.buildFailure(ServiceExceptionEnum.PARAMETER_VERIFICATION_FAILED.getCode(), ServiceExceptionEnum.PARAMETER_VERIFICATION_FAILED.getMessage().replace("msg",msgError.toString()));
    }

//    /**
//     * 权限校验异常
//     */
//    @ExceptionHandler(AccessDeniedException.class)
//    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
//        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
//    }
//
//    /**
//     * 请求方式不支持
//     */
//    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
//    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
//                                                          HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
//        return AjaxResult.error(e.getMessage());
//    }
//
//    /**
//     * 业务异常
//     */
//    @ExceptionHandler(ServiceException.class)
//    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
//        log.error(e.getMessage(), e);
//        Integer code = e.getCode();
//        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
//    }
//
//    /**
//     * 请求路径中缺少必需的路径变量
//     */
//    @ExceptionHandler(MissingPathVariableException.class)
//    public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
//        return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
//    }
//
//    /**
//     * 请求路径中缺少必需的路径变量
//     */
//    @ExceptionHandler(SQLSyntaxErrorException.class)
//    public AjaxResult handleSQLSyntaxErrorException(SQLSyntaxErrorException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("sql语法执行异常'{}',发生系统异常.", requestURI, e);
//        return AjaxResult.error(String.format("执行异常[%s],请联系管理员处理", e.getMessage()));
//    }
//
//    /**
//     * 请求参数类型不匹配
//     */
//    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
//    public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
//        return AjaxResult.error(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
//    }
//
//    /**
//     * 拦截未知的运行时异常
//     */
//    @ExceptionHandler(RuntimeException.class)
//    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',发生未知异常.", requestURI, e);
//        return AjaxResult.error(e.getMessage());
//    }
//
//    /**
//     * 系统异常
//     */
//    @ExceptionHandler(Exception.class)
//    public AjaxResult handleException(Exception e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',发生系统异常.", requestURI, e);
//        return AjaxResult.error(e.getMessage());
//    }
//
//    /**
//     * 自定义验证异常
//     */
//    @ExceptionHandler(BindException.class)
//    public AjaxResult handleBindException(BindException e) {
//        log.error(e.getMessage(), e);
//        String message = e.getAllErrors().get(0).getDefaultMessage();
//        return AjaxResult.error(message);
//    }

    @ExceptionHandler(value = ServiceException.class)
    public Response handleServiceException(ServiceException exp) {
        return Response.buildFailure(exp.getCode(), exp.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Response handleException(Exception exp) {
        log.error("error",exp);
        return Response.buildFailure(ServiceExceptionEnum.SYSTEM_ERROR.getCode(), ServiceExceptionEnum.SYSTEM_ERROR.getMessage());
    }
}
